package com.yami.shop.config;

import com.defipay.api.client.DefipayApiClientFactory;
import com.defipay.api.client.DefipayApiRestClient;
import com.defipay.api.client.domain.ApiResponse;
import com.defipay.api.client.domain.request.CreateOrderRequest;
import com.defipay.api.client.domain.response.CreateOrderResponse;
import com.defipay.api.client.impl.LocalSigner;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.common.bean.FaTPay;
import com.yami.shop.common.bean.FaTPayEnv;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.service.SysConfigService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@AllArgsConstructor
public class FaTPayConfig {

  private final ShopConfig shopConfig;
  private final SysConfigService sysConfigService;

  public DefipayApiRestClient getClient() {
    FaTPayEnv faTPay = shopConfig.getFaTPay();
    return DefipayApiClientFactory.newInstance(new LocalSigner(faTPay.getPrivateKey()), faTPay.getEnv(),
            faTPay.isMode())
        .newRestClient();
  }

  public CreateOrderResponse createOrder(PayInfoDto payInfoDto) {
    DefipayApiRestClient client = getClient();
    CreateOrderRequest request = new CreateOrderRequest();
    request.setNotifyUrl(payInfoDto.getApiNoticeUrl());
    request.setReturnUrl(payInfoDto.getReturnUrl());
    request.setAmount(String.valueOf(payInfoDto.getPayAmount()));
    request.setCurrency("EUR");
    request.setPayMode(3);
    request.setMemberTransNo(payInfoDto.getPayNo());
    ApiResponse<CreateOrderResponse> response = client.createOrder(request);
    if(response.isSuccess()){
      return response.getResult();
    }else {
      log.error("调用faTPay订单创建失败，失败原因：{}", response.toString());
      throw new YamiShopBindException("yami.shop.pay.info.update.error");
    }
  }
}
